package com.xxmw.transaction.controller.app;

import com.xxmw.transaction.common.annotation.UserLoginIgnore;
import com.xxmw.transaction.common.entity.R;
import com.xxmw.transaction.common.utils.Constant;
import com.xxmw.transaction.service.app.MessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;


/**
 * 发送验证码
 */
@RestController
@RequestMapping("/app/message")
@Api(tags = "验证码相关接口")
public class MessageController {
	
	@Autowired
	private MessageService messageService;

	/**
	 * 发送
	 * @param username 用户名
	 * @param type 验证码状态
	 * @return
	 */
	@GetMapping("/send")
	@UserLoginIgnore
	@ApiOperation("发送验证码")
	public R send(@RequestParam Integer type,
			@NotBlank(message = "用户名不能为空!") @RequestParam("username") String username) {
		messageService.send(username, type);
		return R.ok();
	}
	
	/**
	 * 校验验证码
	 * @param username 用户名
	 * @param code 验证码
	 * @return
	 */
	@GetMapping("/sign")
	@UserLoginIgnore
    @Deprecated
	public R sign(@NotBlank(message = "用户名不能为空!") @RequestParam("username")String username,
			@NotBlank(message = "验证码不能为空!") @RequestParam("code") String code) {
		if(!code.matches("\\d")) {
			return R.error("验证码格式有误,请重新输入!");
		}
		String result = messageService.get(username, Constant.Text.SIGN);
		if(result == null) {
			return R.error("验证码已失效!");
		}
		if(!result.equals(code)) {
			return R.error("验证码不正确,请重新输入!");
		}
		return R.ok();
	}
}
